﻿module Sustainalytics.CompanySearch.Admin {
    import Common = Sustainalytics.Common;

    // Company search service
    export class CompanyAdminService implements ICompanyAdminService {
        //private accountId: string;
        //private userId: string;

        // Ctor.
        public constructor(
            private $http: ng.IHttpService,
            private $q: ng.IQService,
            private $rootScope: ng.IScope,
            private notificationFactory: Common.INotificationFactory,
            private staticObjects: Common.IStaticObjects,
            private UserInfoService: Authentication.IUserInfoService) {

            this.$q = $q;
            this.notificationFactory = notificationFactory;
            this.staticObjects = staticObjects;
            this.$rootScope = $rootScope;
        }

        // show error message for a given error code
        private showError(err) {
            var ctx = this;
            if (err && err['errorCode'])
                ctx.notificationFactory.error('', ctx.staticObjects.getErrorMesageByStatusCode(err['errorCode'], err['errorCode']));
        }

        private showMessage(msg) {
            var ctx = this;
            ctx.notificationFactory.success(msg);
        }

        // Search companies
        public search(term: string, skip: number, take: number): ng.IHttpPromise<CorporateDataExtendedDto[]> {
            var ctx = this;
            var urlParams = jQuery.param(
                {
                    userId: ctx.UserInfoService.getUserInfo().userId,
                    accountId: ctx.UserInfoService.getUserInfo().accountId,
                    term: term,
                    skip: skip,
                    take: take,
                    fromAdmin: true
                });

            var url: string = '/companyserv/api/v1/companies?' + urlParams;

            var lstPromise: ng.IHttpPromise<CorporateDataExtendedDto[]> = this.$http.get(url);

            return lstPromise;
        }

        // Get all companies
        public getCompanies(term: string, skip: number, take: number, orderBy: string, orderByAsc: boolean, hasResearch: boolean) {
            var ctx = this;
            var def = this.$q.defer();

            var urlParams = jQuery.param(
                {
                    userId: ctx.UserInfoService.getUserInfo().userId,
                    accountId: ctx.UserInfoService.getUserInfo().accountId,
                    term: term,
                    skip: skip,
                    take: take,
                    includeFullData : true,
                    getCount: false,
                    orderBy: orderBy,
                    orderAscending: orderByAsc,
                    isGrid: true,
                    hasResearch: hasResearch
                });

            var url: string = '/companyserv/api/v1/companies?' + urlParams;

            var promise = this.$http.get(url);

            promise.success(
                function(data) {
                    def.resolve(data);
                }).error(
                function(err) {
                    ctx.showError(err);
                    def.reject();
                });

            return def.promise;
        }

        //Get company count
        public getCompaniesCount(term: string, hasResearch: boolean) {
            var ctx = this;
            var def = this.$q.defer();

            var urlParams = jQuery.param(
                {
                    userId: ctx.UserInfoService.getUserInfo().userId,
                    accountId: ctx.UserInfoService.getUserInfo().accountId,
                    term: term,
                    getCount: true,
                    hasResearch: hasResearch
                });

            var url: string = '/companyserv/api/v1/companies?' + urlParams;

            var lstPromise = this.$http.get(url);

            lstPromise.success(
                function (data) {
                    def.resolve(data);
                }).error(
                function (err) {
                    ctx.showError(err);
                    def.reject();
                })

            return def.promise;
        }

        public getById(id: string, accountFeature?: Common.AccountFeature): ng.IHttpPromise<CorporateDataExtendedDto> {

            var url: string = 'companyserv/api/v1/companies/' + id + '?feature=' + accountFeature;

            var promise: ng.IHttpPromise<Sustainalytics.Company.CorporateDataExtendedDto> = this.$http.get(url);

            return promise;
        }

        public getByNameUrlFriendly(companyName: string, includeFullData?: boolean): ng.IHttpPromise<CorporateDataExtendedDto> {
            var ctx = this;
            var def = this.$q.defer();

            var params =
                {
                    userId: ctx.UserInfoService.getUserInfo().userId,
                    accountId: ctx.UserInfoService.getUserInfo().accountId,
                    term: companyName,
                    exactMatch: true,
                    byFriendlyName: true
                };

            if (typeof(includeFullData) !== 'undefined' && includeFullData != null) {
                params['includeFullData'] = includeFullData;
            }

            var args = $.param(params);

            var url: string = 'companyserv/api/v1/companies?' + args;

            var promise: ng.IHttpPromise<CorporateDataExtendedDto> = this.$http.get(url);

            promise.success(function (data) {
                def.resolve(data);
            })
                .error(function (err) {
                    if(includeFullData)
                        ctx.showError(err);
                    def.reject();
                })

            return promise;
        }
    }


    // get/create company search module
    angular.module('Sustainalytics.CompanySearch.Admin').service('CompanyAdminService',
        ['$http', '$q', '$rootScope', 'notificationFactory', 'staticObjects', 'UserInfoService', CompanyAdminService]);
}